package com.psp.stock.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

import cn.hutool.core.date.DateUtil;
import com.psp.stockprice.mapper.StockPriceMapper;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.psp.stock.mapper.StockMapper;
import com.psp.stock.domain.Stock;
import com.psp.stock.service.IStockService;

import javax.annotation.Resource;

/**
 * 股票基础信息Service业务层处理
 *
 * @author psp
 */
@Service
public class StockServiceImpl implements IStockService {

    private static final Logger log = LoggerFactory.getLogger(StockServiceImpl.class);

    @Resource
    private StockMapper stockMapper;

    @Resource
    private StockPriceMapper stockPriceMapper;

    /**
     * 查询股票基础信息
     *
     * @param id 股票基础信息主键
     * @return 股票基础信息
     */
    @Override
    public Stock selectStockById(String id) {
        return stockMapper.selectStockById(id);
    }

    /**
     * 查询股票个数
     *
     * @return 股票个数
     */
    @Override
    public int selectStockCount() {
        return stockMapper.selectStockCount();
    }

    /**
     * 查询股票基础信息列表
     *
     * @param stock 股票基础信息
     * @return 股票基础信息
     */
    @Override
    public List<Stock> selectStockList(Stock stock) {
        return stockMapper.selectStockList(stock);
    }

    /**
     * 批量新增或修改股票信息
     *
     * @param stockList 待新增或修改股票
     */
    @Override
    public void batchInsertOrUpdate(List<Stock> stockList) {

        List<Stock> updateList = new ArrayList<>();
        List<Stock> addList = new ArrayList<>();
        List<Stock> dbList = this.selectStockList(new Stock());

        // 数据在数据库中存在股票编码则更新,不存在则新增
        stockList.forEach(n -> {
            Optional<Stock> optional = dbList.stream().filter(b -> n.getStockCode().equals(b.getStockCode())).findFirst();
            if (optional.isPresent()) {
                //该股票code在数据库中已经存在，仅更新股票名称
                optional.get().setStockName(n.getStockName());
                optional.get().setUpdateTime(DateUtil.date());
                updateList.add(optional.get());
            } else {
                //数据库中无此股票
                addList.add(n);
            }
        });
        if (addList.size() > 0) {
            this.batchInsertStock(addList);
        }
        if (updateList.size() > 0) {
            this.batchUpdateStock(updateList);
        }
    }

    /**
     * 查询股票基础信息列表,不包含股票型基金
     */
    @Override
    public List<Stock> selectStockListExcludeFund() {
        return stockMapper.selectStockListExcludeFund();
    }

    /**
     * 新增股票基础信息
     *
     * @param stock 股票基础信息
     * @return 结果
     */
    @Override
    public int insertStock(Stock stock) {
        stock.setId(IdUtils.fastSimpleUUID());
        stock.setCreateTime(DateUtils.getNowDate());
        return stockMapper.insertStock(stock);
    }

    /**
     * 导入股票数据
     */
    @Override
    public void batchInsertStock(List<Stock> stockList) {
        Date beginDate = new Date();
        log.info("开始批量导入股票数据:" + DateUtil.now());

        if (stockList == null) return;
        //校验是否有股票code和股票名称字段
        if (stockList.get(0) == null) {
            throw new ServiceException("导入失败,没有找到任何匹配的导入字段!");
        } else {
            if (StringUtils.isEmpty(stockList.get(0).getStockCode())) {
                throw new ServiceException("导入失败,股票code不能为空!");
            } else if (StringUtils.isEmpty(stockList.get(0).getStockName())) {
                throw new ServiceException("导入失败,股票名称不能为空!");
            }
        }

        stockList.forEach(n -> {
            n.setId(IdUtils.fastSimpleUUID());
            n.setCreateTime(DateUtil.date());
        });
        int n = stockMapper.batchInsertStock(stockList);

        log.info("导入{}条股票数据用时:{}毫秒", n, DateUtil.betweenMs(beginDate, new Date()));
    }

    /**
     * 修改股票基础信息
     *
     * @param stock 股票基础信息
     * @return 结果
     */
    @Override
    public int updateStock(Stock stock) {
        stock.setUpdateTime(DateUtils.getNowDate());
        return stockMapper.updateStock(stock);
    }

    /**
     * 批量更新股票信息
     */
    @Override
    public void batchUpdateStock(List<Stock> updateList) {
        Date beginDate = new Date();
        log.info("开始批量更新股票数据:" + DateUtil.now());
        stockMapper.batchUpdateStock(updateList);
        log.info("批量更新{}条股票数据用时:{}毫秒", updateList.size(), DateUtil.betweenMs(beginDate, new Date()));
    }

    /**
     * 批量删除股票信息同时删除历史价格
     *
     * @param ids 需要删除的股票基础信息主键
     * @return 结果
     */
    @Override
    public int deleteStockByIds(String[] ids) {
        for (String id : ids) {
            stockPriceMapper.deleteStockPriceByCode(stockMapper.selectStockById(id).getStockCode());
        }
        stockMapper.deleteStockByIds(ids);
        return ids.length;
    }

    @Override
    public void clearStockData() {
        stockMapper.clearStockData();
    }

    /**
     * 删除股票基础信息信息
     *
     * @param id 股票基础信息主键
     * @return 结果
     */
    @Override
    public int deleteStockById(String id) {
        return stockMapper.deleteStockById(id);
    }
}
